package com.example.choupaiapp.main.activity.mine;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.GsonUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.QQLoginBean;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.WechatLoginBean;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.QQLoginUtil;
import com.example.choupaiapp.main.util.WechatLoginUtil;
import com.example.choupaiapp.main.util.WeiboLoginUtil;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/10/31.
 */

public class SafeCenterActivity extends CommonActivity implements WechatCallBack {

    @BindView(R.id.is_bind_wechat)
    TextView isBindWechat;
    @BindView(R.id.is_bind_weibo)
    TextView isBindWeibo;
    @BindView(R.id.is_bind_qq)
    TextView isBindQq;
    private UserInfoBean userInfoBean;
    private String loginFlag = "";
    private SelfWbAuthListener weiboListener;
    private BaseUiListener listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safe_center);

    }

    @Override
    protected void initView() {
        setTitle("安全中心");
        EventBus.getDefault().register(this);
        userInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        if (!TextUtils.isEmpty(userInfoBean.getUser().getWechatOpenid())) {
            isBindWechat.setText("已绑定");
        } else {
            isBindWechat.setText("去绑定");
        }

        if (!TextUtils.isEmpty(userInfoBean.getUser().getQqOpenid())) {
            isBindQq.setText("已绑定");
        } else {
            isBindQq.setText("去绑定");
        }

        if (!TextUtils.isEmpty(userInfoBean.getUser().getSinaOpenid())) {
            isBindWeibo.setText("已绑定");
        } else {
            isBindWeibo.setText("去绑定");
        }
    }

    @Override
    protected void initData() {

    }


    //    @Override
    @OnClick({R.id.bind_wechat, R.id.bind_weibo, R.id.bind_qq})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.bind_wechat:
                if (!TextUtils.isEmpty(userInfoBean.getUser().getWechatOpenid())) {
//                    unbind(1);
                } else {
                    if (WechatLoginUtil.getInstance().isWeChatAppInstalled()) {
                        showDialog(this, "登录中...");
                        loginFlag = "wechat";
                        WechatLoginUtil.getInstance().setWechatCallBack(this);
                        WechatLoginUtil.getInstance().wechatLogin();
                    } else {
                        showImageToas("请先安装微信客户端");
                    }
                }
                break;
            case R.id.bind_weibo:
                if (!TextUtils.isEmpty(userInfoBean.getUser().getSinaOpenid())) {
//                    unbind(3);
                } else {
                    showDialog(this, "绑定中...");
                    loginFlag = "weibo";
                    weiboListener = new SelfWbAuthListener();
                    WeiboLoginUtil.getInstance().weiboLogin(this, weiboListener);
                }
                break;
            case R.id.bind_qq:
                if (!TextUtils.isEmpty(userInfoBean.getUser().getQqOpenid())) {
//                    unbind(2);
                } else {
                    if (QQLoginUtil.getInstance().isQQAppInstalled()) {
                        showDialog(this, "绑定中...");
                        loginFlag = "qq";
                        listener = new BaseUiListener();
                        QQLoginUtil.getInstance().qqLogin(this, listener);
                    } else {
                        showImageToas("请先安装qq客户端");
                    }
                }
                break;
        }
    }

    private void unbind(int type) {
        showDialog(context, "解绑中...");
        HttpParams params = new HttpParams();
        params.put("type", type);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.UNBIND_LOGIN, params, Url.UNBIND_LOGIN, new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                dismissDialog();
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    EventBus.getDefault().post("refresh_mine");
                    if (type == 1) {
                        userInfoBean.getUser().setWechatOpenid("");
                        SharedPreferencesHelp.put("weChat_token", "");
                        isBindWechat.setText("去绑定");
                    } else if (type == 2) {
                        userInfoBean.getUser().setQqOpenid("");
                        isBindQq.setText("去绑定");
                    } else if (type == 3) {
                        userInfoBean.getUser().setSinaOpenid("");
                        isBindWeibo.setText("去绑定");
                    }
                } else {
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("finish_safe_center")) {
            finishActivity();
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object value) {

            QQLoginBean qqLoginBean = GsonUtil.jsonStringToClassWithGson(value.toString(), QQLoginBean.class);

            if (qqLoginBean.getRet() == 0) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("qqOpenid", qqLoginBean.getOpenid());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_BIND_LOGIN, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        dismissDialog();
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            userInfoBean.getUser().setQqOpenid(qqLoginBean.getOpenid());
                            isBindQq.setText("已绑定");
                            EventBus.getDefault().post("refresh_mine");
                        } else {
                            if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                            } else {
                                showImageToas(sendCodeBean.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Response response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
            } else {
                dismissDialog();
                showImageToas("授权失败");
            }


        }

        @Override
        public void onError(UiError uiError) {
            showImageToas("授权失败");
        }

        @Override
        public void onCancel() {
            showImageToas("取消授权");
        }
    }

    private class SelfWbAuthListener implements com.sina.weibo.sdk.auth.WbAuthListener {
        @Override
        public void onSuccess(final Oauth2AccessToken token) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("sinaOpenid", token.getUid());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_BIND_LOGIN, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                @Override
                public void onSuccess(SendCodeBean sendCodeBean) {
                    dismissDialog();
                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                        userInfoBean.getUser().setSinaOpenid(token.getUid());
                        isBindWeibo.setText("已绑定");
                        EventBus.getDefault().post("refresh_mine");
                    } else {
                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                        } else {
                            showImageToas(sendCodeBean.getMsg());
                        }
                    }
                }

                @Override
                public void onError(Response response) {
                    super.onError(response);
                    dismissDialog();
                }
            });
        }

        @Override
        public void cancel() {
            showImageToas("取消授权");
        }

        @Override
        public void onFailure(WbConnectErrorMessage errorMessage) {
            showImageToas("授权失败");
            Logger.e(errorMessage.getErrorCode() + "---" + errorMessage.getErrorMessage());
        }
    }


    @Override
    public void callBack(BaseResp baseResp) {
        String result = "";
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
                finalOkGo.request(RequestType.GET,
                        "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Config.WEIXIN_APP_ID
                                + "&secret=" + Config.WEIXIN_APP_SCRECT + "&code=" + newResp.code
                                + "&grant_type=authorization_code", null, "wechatLogin", new Callback<WechatLoginBean>() {
                            @Override
                            public void onSuccess(WechatLoginBean wechatLoginBean) {
                                if (wechatLoginBean != null && wechatLoginBean.getOpenid() != null && !TextUtils.isEmpty(wechatLoginBean.getOpenid())) {
                                    finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Config.WEIXIN_APP_ID
                                                    + "&grant_type=refresh_token&refresh_token=" + wechatLoginBean.getRefresh_token(), null, "refresh_token",
                                            new Callback<WechatLoginBean>() {
                                                @Override
                                                public void onSuccess(WechatLoginBean refresh) {
                                                    if (refresh != null && refresh.getOpenid() != null && !TextUtils.isEmpty(refresh.getOpenid())) {
                                                        JSONObject jsonObject = new JSONObject();
                                                        try {
                                                            jsonObject.put("wechatOpenid", refresh.getOpenid());
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_BIND_LOGIN, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                                            @Override
                                                            public void onSuccess(SendCodeBean sendCodeBean) {
                                                                dismissDialog();
                                                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                                    SharedPreferencesHelp.put("weChat_token", refresh.getRefresh_token());
                                                                    userInfoBean.getUser().setWechatOpenid(refresh.getOpenid());
                                                                    isBindWechat.setText("已绑定");
                                                                    EventBus.getDefault().post("refresh_mine");
                                                                } else {
                                                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                                                    } else {
                                                                        showImageToas(sendCodeBean.getMsg());
                                                                    }
                                                                }
                                                            }

                                                            @Override
                                                            public void onError(Response response) {
                                                                super.onError(response);
                                                                dismissDialog();
                                                            }
                                                        });
                                                    } else {
                                                        dismissDialog();
                                                        showImageToas("绑定失败");
                                                    }
                                                }

                                                @Override
                                                public void onError(Response<String> response) {
                                                    super.onError(response);
                                                    dismissDialog();
                                                }
                                            });

                                } else {
                                    dismissDialog();
                                    showImageToas("绑定失败");
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                dismissDialog();
                result = "发送取消";
                showImageToas(result);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                dismissDialog();
                result = "发送被拒绝";
                showImageToas(result);
                break;
            default:
                dismissDialog();
                result = "发送返回";
                showImageToas(result);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (loginFlag.equals("")) {
            super.onActivityResult(requestCode, resultCode, data);
        } else if (loginFlag.equals("weibo")) {
            if (WeiboLoginUtil.mSsoHandler != null) {
                WeiboLoginUtil.mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        } else if (loginFlag.equals("qq")) {
            if (requestCode == Constants.REQUEST_LOGIN ||
                    requestCode == Constants.REQUEST_APPBAR) {
                Tencent.onActivityResultData(requestCode, resultCode, data, listener);
            }
        }

    }
}
